package com.db;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.exception.DBException;

public final class JdbcUtil
{
	private static String username = "root"; //default value is root
	private static String password = "root"; //default value is root

	private static String propFileName = "/com/util/connDB.properties";
	private static Properties prop = new Properties();
	private static String dbClassName = "com.mysql.jdbc.Driver";
	private static String dbUrl = "jdbc:mysql://127.0.0.1:3306/Lab";

	static
	{
		/* get inputstream from the database config file */
		try
		{   
			InputStream in =new JdbcUtil().getClass().getResourceAsStream(propFileName);
			prop.load(in);
			in.close();
		}
		catch (IOException e1)
		{
			e1.printStackTrace(System.err);
		}
		/* read the class name and url from configuration file */
		
		dbClassName = prop.getProperty("DB_CLASS_NAME");
		dbUrl = prop.getProperty("DB_URL", "jdbc:mysql://127.0.0.1:3306/Lab");
		username = prop.getProperty("USERNAME");
		password = prop.getProperty("PASSWORD");

		try
		{
			Class.forName(dbClassName);
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws DBException 
	{
		try
		{
			return DriverManager.getConnection(dbUrl, username, password);
		}
		catch (SQLException e)
		{
			throw new DBException("Fail to connect the database;");
		}
	}

	public static void free(ResultSet rs, Statement stmt, Connection con)
	{

		try
		{
			if (rs != null)
				rs.close();
			if (stmt != null)
				stmt.close();
			if (con != null)
				con.close();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}

	}

}
